// Add an item to the array associated with the specified key.  If an
// array isn't associated with the key it is created.
function DictionaryTree_add(key, item) {
  var child;
  if (!this.exists(key)) {
    child = new DictionaryTree();
    DictionaryTree.prototype.bases[0].add.call(this, key, child);
  } else {
    child = this.item(key);
  }
  if (!isUndefined(item)) {
    // If the item is an array containing a key value pair.
    if ((item instanceof Array) && item.length == 2) {
      child.add(item[0], item[1]);
      return;
    }
    // If the item is an associative array.
    if (item instanceof Object) {
      var key_value = [];
      for (i in item) {
        key_value.push(i)
        key_value.push(item[i])
      }
      if (key_value.length == 2) {
        child.add(key_value[0], key_value[1]);
      }
      return;
    }
    // Just add the item.
    child.add(item);
  }
}

// Remove an item from an array associate with a key.  When the array
// associate with a key is empty the array is removed from the dictionary.
// If no item is specified the key and array are removed.
function DictionaryTree_remove(key, item) {
  if (isUndefined(item)) {
    return DictionaryTree.prototype.bases[0].remove.call(key);
  }
  var child = this.get(key);
  if (isUndefined(child)) {
    throw 'Key ' + key.toString() + ' not found';
  }
  var value = child.get(item);
  if (isUndefined(value)) {
    throw 'Item ' + item.toString() + ' not found';
  }
  child.remove(item);
  if (child.length == 0) {
    this.remove(key);
  }
}

// Constructor.
function DictionaryTree(associative_array) {
  // Call the base class' constructor.
  Dictionary.call(this, associative_array);
}

// Inherit from Dictionary and fix up the class methods.
addBase(inherit(DictionaryTree, Dictionary), Dictionary);
DictionaryTree.prototype.add = DictionaryTree_add;
DictionaryTree.prototype.remove = DictionaryTree_remove;
